<template>
  <div
    :ref="refName"
    :optionData="optionData"
    :title="title"
    style="width: 100%; height: 100%"
  />
</template>

<script>
import * as echarts from "echarts";
export default {
  props: {
    refName: {
      type: String,
      default: "ref",
    },
    optionData: {
      type: Object,
    },
    title: {
      type: String,
      default: "",
    },
  },
  data() {
    return {
      chartData: null,
      namelist: [],
      serieslist: [],
      yAxislist: [],
    };
  },
  watch: {
    optionData(newVal) {
      this.chartData = newVal;
      this.namelist = this.chartData.nameAndListValueDtos.map((res) => {
        return res.name;
      });
      this.serieslist = this.chartData.nameAndListValueDtos.map((res) => {
        const commonProps = {
          name: res.name,
          type: res.type,
          emphasis: {
            focus: "series",
          },
          data: res.values,
        };
        return res.yAxisIndex
          ? {
              ...commonProps,
              data: res.values,
            }
          : {
              ...commonProps,
              data: res.values,
              barWidth: 20,
            };
      });
      this.init();
    },
  },
  mounted() {},
  methods: {
    init() {
      const myChart = echarts.init(this.$refs[this.refName]);

      const option = {
        graphic: [
          {
            type: "text",
            left: "5%",
            top: "5%",
            style: {
              text: this.title,
              fontSize: 20,
            },
          },
        ],
        tooltip: {
          trigger: "axis",
          axisPointer: {
            type: "cross",
            crossStyle: {
              color: "#999",
            },
          },
        },
        legend: {
          right: "5%",
          top: "5%",
          data: this.namelist,
        },
        grid: {
          top: "20%",
          bottom: "10%",
        },
        xAxis: [
          {
            type: "category",
            data: this.chartData != null ? this.chartData.dateStrs : [],
            axisPointer: {
              type: "shadow",
            },
            axisTick: {
              show: false,
            },
          },
        ],
        yAxis: this.optionData.yAxis || [],
        series: this.serieslist,
      };

      option && myChart.setOption(option);
      myChart.on("click", (event) => {
        console.log("单击事件触发", event);
      });
    },
  },
};
</script>
